<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select v-model="listQuery.paymentStatus" :placeholder="$t('table.paymentStatus')" clearable class="filter-item"
        style="width: 130px" @change="getList">
        <el-option v-for="item in paymentStatuss" :key="item" :label="$t('table.'+item)" :value="item" />
      </el-select>
      <el-select v-model="listQuery.sort" style="width: 140px" class="filter-item" @change="handleFilter">
        <el-option v-for="item in sortOptions" :key="item.key" :label="item.label" :value="item.key" />
      </el-select>
      <el-input
      v-model="listQuery.keyword"
      :placeholder="$t('table.keyword')"
      style="width: 200px;"
      class="filter-item"
      @keyup.enter.native="handleFilter"
    />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        {{ $t('table.search') }}
      </el-button>
      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download"
        @click="handleDownload">
        {{ $t('table.export') }}
      </el-button>
    </div>

    <el-table :key="tableKey" v-loading="listLoading" :data="list" border fit highlight-current-row style="width: 100%;"
    ref="dragTable">
      <el-table-column :label="$t('table.orderId')" prop="orderId" sortable="custom" align="center" width="125"
        :class-name="getSortClass('id')">
        <template slot-scope="{row}">
          <span>{{ row.orderId }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.total')" width="100px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.total }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.email')"  min-width="120px" align="center">
        <template slot-scope="{row}">
          <span>
            {{row.userEmail}}
          </span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.paymentStatus')" class-name="status-col" width="120">
        <template slot-scope="{row}">
          <el-tag class="heffect" :type="row.paymentStatus | paymentStatusFilter">
            {{ $t('table.'+row.paymentStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.date')" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.created_at | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column  fixed="right" :label="$t('table.actions')" align="center" width="150" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button v-if="row.status != 'deleted'" size="mini" type="danger" @click="handleDelete(row, $index)">
            {{ $t('table.delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
      @pagination="getList" />

    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">{{ $t('table.confirm') }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getOrderListByPage, fetchPv, addOrder, updateOrder, deleteOrder } from '@/api/order'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import i18n from '@/lang'
import { getToken } from '@/utils/auth'

const calendarTypeOptions = [
  { key: 'enabled', display_name: i18n.t('table.enabled') },
  { key: 'disabled', display_name: i18n.t('table.disabled') }
]

// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'ComplexTable',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        enabled: 'success',
        disabled: 'danger'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    },
    orderStatusFilter(status){
      const statusMap = {
        pending_payment: 'info',
        pending_usage: '',
        completed: 'success',
        cancelled: 'danger',
      }
      return statusMap[status]
    },
    paymentStatusFilter(status){
      const statusMap = {
        pending_payment: 'info',
        paid: 'success',
        payment_failed: 'danger',
        refounded: 'warning',
      }
      return statusMap[status]
    },
  },
  data() {
    return {
      uploadUrl: process.env.VUE_APP_BASE_API + '/file',
      token: getToken(),
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        keyword: undefined,
        type: undefined,
        sort: 'DESC',
        order: '',
        paymentStatus: '',
        orderStatus: ''
      },
      calendarTypeOptions,
      sortOptions: [{ label: '从新到旧', key: 'DESC' }, { label: '从旧到新', key: 'ASC' }],
      paymentStatuss: [
        'pending_payment', 'paid', 'payment_failed', 'refounded'
      ],
      temp: {
        id: undefined,
        total: '',
        productId: '',
        sort: 0,
        coverFileId: undefined
      },
      productForm: {
        quantity: 1,
        productId: undefined,
        name: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        total: [{ required: true, message: 'total is required', trigger: 'blur' }]
      },
      downloadLoading: false,
      file: null,
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      this.listQuery.t = Date.now()
      getOrderListByPage(this.listQuery).then(res => {
        console.log(res.data, 'res')
        this.list = res.data.rows
        this.listLoading = false
        this.total = res.data.total
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = 'DESC'
      } else {
        this.listQuery.sort = 'ASC'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        status: 'enabled',
        productId: null,
        sort: 0,
        coverFileId: undefined
      }
      this.file = null
      this.resetProductForm()
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.sort = Number(this.temp.sort)
          addOrder(this.temp).then(res => {
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
            this.dialogFormVisible = false
            this.getList()
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = JSON.parse(JSON.stringify(row))
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.sort = Number(this.temp.sort)
          updateOrder(this.temp).then(res => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    handleDelete(row, index) {
      this.$confirm('确认删除?').then(() => {
        deleteOrder(row.orderId).then(res => {
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          this.getList()
        })
      })
    },
    handleFetchPv(pv) {
      fetchPv(pv).then(response => {
        this.pvData = response.data.pvData
        this.dialogPvVisible = true
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = [i18n.t('table.orderId'), i18n.t('table.remarks'), i18n.t('table.nickname'), i18n.t('table.total'), i18n.t('table.orderStatus'), i18n.t('table.paymentStatus')]
        const filterVal = ['orderId', 'remarks', 'nickname', 'total', 'orderStatus', 'paymentStatus']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'order-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'nickname') {
          return v.user.nickname
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function (key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    },
    onUploadSuccess(e) {
      if (e?.code === 200) {
        this.$message.success(e.msg)
        this.file = e.data
        this.temp.coverFileId = e.data.id
      } else {
        this.$message.error(e.msg)
      }
    },
    onUploadError(e) {
      this.$message.error(e.msg || 'faild')
    },
    handleProdClose(id){
      let index = this.temp.orderItems?.findIndex(obj => obj.id === id)
      this.temp.orderItems.splice(index, 1)
    },
    handleAddProduct(){
      if(this.productForm.productId){
        this.temp.orderItems.push(JSON.parse(JSON.stringify(this.productForm)))
        this.resetProductForm()
      }else{
        this.$message.info('请选择商品')
      }
    },
    resetProductForm(){
      this.productForm = {
          quantity: 1,
          productId: undefined,
          name: ''
        }
    }
  }
}
</script>

<style>
.sortable-ghost {
  opacity: .8;
  color: #fff !important;
  background: #42b983 !important;
}
.el-tag  {
  height: fit-content;
}
</style>

<style scoped>
.icon-star {
  margin-right: 2px;
}

.drag-handler {
  width: 20px;
  height: 20px;
  cursor: pointer;
}

.show-d {
  margin-top: 15px;
}
</style>

